<template>
     <div class="home-container">

    <van-nav-bar
    title="编辑资料"
    left-arrow
     @click-left="$router.back()"
    fixed
    class="header"
  />
    <van-cell title="头像" >
  <!-- 使用 right-icon 插槽来自定义右侧图标 -->

   <template #default>
          <van-image round class="avatar" :src="userSimpleInfo.photo" @click="$refs.fileRef.click()"/>
          <input type="file" accept="image/*" @change="onFileChange" v-show="false" ref="fileRef" />
  </template>
</van-cell>

    <van-cell title="名称" is-link :value="userSimpleInfo.name"  @click="clickName"/>
      <van-dialog v-model="show" title="标题" show-cancel-button  :before-close="beforeClose">>
      <van-field v-model.trim="name" placeholder="请输入用户名" input-align="center" maxlength="11" ref="nameRef"  />
      </van-dialog>

    <van-cell title="生日" is-link :value="userSimpleInfo.birthday" @click="showBirthday"/>
    <van-action-sheet v-model="isBirthdayShow" >
    <van-datetime-picker
  v-model="currentDate"
  type="date"
  title="选择生日"
  :min-date="minDate"
  :max-date="maxDate"
  @confirm="updateBirthday"
 @cancel="showBirthSheet = false"
/>
</van-action-sheet>
</div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import { updataUserInfo } from '../API/userInfo'
import { upUserPhoto } from '../API/userAPI.js'
// 导入 dayjs
import dayjs from 'dayjs'
export default {
  name: 'edit',

  data () {
    return {
      name: '',
      show: false,
      isBirthdayShow: false,

      // 最小可选日期（0 表示 1月份）
      minDate: new Date(1900, 0, 1),
      // 最大可选日期（11 表示 12月份）
      maxDate: new Date(2050, 11, 31),
      // 当前日期
      currentDate: new Date()
    }
  },
  methods: {
    ...mapActions(['initSimpleUserInfo']),
    // 显示生日弹窗
    showBirthday () {
      // 如果用户生日的值存在，则初始值为用户的生日；否则为当前日期
      this.currentDate = this.userSimpleInfo.birthday ? new Date(this.userSimpleInfo.birthday) : new Date()
      this.isBirthdayShow = true
    },
    async updateBirthday (value) {
      this.isBirthdayShow = false
      const dateStr = dayjs(value).format('YYYY-MM-DD')
      // 打印用户选择的日期

      const { data: res } = await updataUserInfo({ birthday: dateStr })
      if (res.message === 'OK') {
        // 重新获取用户的简介信息
        this.initSimpleUserInfo()
        // 提示用户更新成功
        this.$notify({ type: 'success', message: '生日修改成功！', duration: 2000 })
      }
    },
    beforeClose (action, done) {
      if (action === 'cancel') return done()
      if (this.name === '' || this.name.length > 11) {
        // 1. 提示用户“名称的长度为1-7个字符”
        this.$notify({ type: 'warning', message: '名称的长度为1-7个字符', duration: 2000 })
        // 2. 让文本框持续获得焦点
        this.$refs.nameRef.focus()
        // 3. 阻止对话框关闭
        return done(false)
      }
      this.updataName(done)
      done()
    },
    async updataName (done) {
      try {
        const { data: res } = await updataUserInfo({ name: this.name })
        if (res.message === 'OK') {
          done()
        }
        // 2. 重新请求用户的简介信息
        this.initSimpleUserInfo()
        // 3. 提示用户更新成功
        this.$notify({ type: 'success', message: '名称更新成功！', duration: 2000 })
      } catch (e) {
        if (e.response.status === 409) {
          this.$notify({ type: 'warning', message: '名称被占用，请更换后重试！', duration: 2000 })
          // 阻止关闭对话框
          done(false)
          this.$refs.nameRef.focus()
        } else {
          // 关闭对话框
          done()
          // 提示用户名称被占用
          this.$notify({ type: 'danger', message: '名称更新失败！', duration: 2000 })
        }
      }
    },
    clickName () {
      this.name = this.userSimpleInfo.name
      this.show = true
      this.$nextTick(() => {
        this.$refs.nameRef.focus()
      })
    },
    // 上传头像
    async onFileChange (e) {
      const files = e.currentTarget.files

      if (files.length === 0) return
      const fd = new FormData()
      // console.log(fd)
      fd.append('photo', files[0])
      // console.log(fd)
      const { data: res } = await upUserPhoto(fd)
      if (res.message === 'OK') {
        this.$notify({ type: 'success', message: '头像更新成功', duration: 2000 })
        this.initSimpleUserInfo()
      }
    },
    // 确认选择的时间
    confirmPicker (val) {
      const year = val.getFullYear()
      let month = val.getMonth() + 1
      let day = val.getDate()
      let hour = val.getHours()
      let minute = val.getMinutes()
      if (month >= 1 && month <= 9) { month = `0${month}` }
      if (day >= 1 && day <= 9) { day = `0${day}` }
      if (hour >= 0 && hour <= 9) { hour = `0${hour}` }
      if (minute >= 0 && minute <= 9) { minute = `0${minute}` }
      this.className = 'timeClass'
      this.timeValue = `${year}-${month}-${day} ${hour}:${minute}`
      this.show = false
    }
  },
  created () {
    this.initSimpleUserInfo()
  },
  computed: {
    ...mapState(['userSimpleInfo'])
  }

}

</script>

<style>
.home-container{
  padding:55.0px 0 59.9992px 0 ;
}
.van-nav-bar .van-icon{
  color: #fff;
}
.van-picker .van-datetime-picker{
  z-index: 2020;
}
.user_pto{
    width: 1.5514rem;
    height:  1.5514rem;
    background-color: #fff;
    border-radius: 50%;

}
.van-image--round{
    width: 1.33333rem;
    height: 1.33333rem;
}
</style>
